package com.mf.framework.component.mybatis.dialect;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Oracle方言实现类
 * User: zhaoming
 * Date: 2017/6/15 10:06
 * To change this template use File | Settings | File Templates.
 */
public class OracleDialect extends Dialect {

    /**
     * 设置分页
     */
    public void setSqlLimit(MetaObject metaObject, BoundSql boundSql, int offset, int limit) {
        Configuration configuration = (Configuration) metaObject.getValue("delegate.configuration");
        //获取SQL
        String sql = trim(boundSql.getSql());
        //获取参数映射
        List<ParameterMapping> parameterMappings = new ArrayList<>();
        if(boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0){
            parameterMappings = boundSql.getParameterMappings();
        }
        //获取参数对象
        Map<String, Object> parameterObject = (Map<String, Object>)boundSql.getParameterObject();
        StringBuffer sqlBuilder = new StringBuffer();
        sqlBuilder.append("select * from ( select row_.*, rownum rownum_ from ( ");
        sqlBuilder.append(sql);
        sqlBuilder.append(" ) row_ ) where rownum_ > ").append("?").append(" and rownum_ <= ").append("?");

        //设置参数映射
        parameterMappings.add(new ParameterMapping.Builder(configuration, "_offset", Integer.class).build());
        parameterMappings.add(new ParameterMapping.Builder(configuration, "_limit", Integer.class).build());
        //设置参数值
        parameterObject.put("_offset", offset);
        parameterObject.put("_limit", offset + limit);

        metaObject.setValue("delegate.boundSql.sql", sqlBuilder.toString());
        metaObject.setValue("delegate.boundSql.parameterMappings", parameterMappings);
        metaObject.setValue("delegate.boundSql.parameterObject", parameterObject);
	}
}
